package api;

import java.io.IOException;
import java.time.Instant;
import java.util.Properties;

import org.json.JSONObject;

import redis.clients.jedis.Jedis;

/**
 * 通宝相关接口
 * 
 * @author 毛建杰
 *
 */
public class PurseApi
{
	private static Properties properties;
	private static String redisIP;
	private static int redisPort;
	private static String redisPassword;
	private static int redisDb;

	static
	{
		try
		{
			properties = new Properties();
			properties.load(PurseApi.class.getResourceAsStream("/gjolshopapi.properties"));
			redisIP = properties.getProperty("redis.ip");
			redisPort = Integer.parseInt(properties.getProperty("redis.port"));
			redisPassword = properties.getProperty("redis.password");
			redisDb = Integer.parseInt(properties.getProperty("redis.db"));
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 游戏向平台发送查询通宝请求
	 * 
	 * @param sid
	 *            服务器ID
	 * @param uid
	 *            用户ID
	 * @param timestemp
	 *            请求时间戳
	 * @throws Exception
	 *             异常
	 */
	public static void msQueue(int sid, int uid, long timestemp) throws Exception
	{
		try (Jedis jedis = new Jedis(redisIP, redisPort))
		{
			jedis.auth(redisPassword);
			jedis.select(redisDb);
			JSONObject request = new JSONObject().put("uid", uid).put("sid", sid).put("time", timestemp);
			System.out.println(request.toString());
			jedis.rpush("MSQueue", request.toString());
		}
		catch (Exception e)
		{
			throw e;
		}
	}

	/**
	 * 游戏向平台获取查询通宝响应
	 * 
	 * @param sid
	 *            服务器ID
	 * @return 查询通宝响应
	 * @throws Exception
	 *             异常
	 */
	public static String msQueueResult(int sid) throws Exception
	{
		try (Jedis jedis = new Jedis(redisIP, redisPort))
		{
			jedis.auth(redisPassword);
			jedis.select(redisDb);
			String response = jedis.lpop("MSQueue:" + sid);
			return response;
		}
		catch (Exception e)
		{
			throw e;
		}
	}

	public static void main(String[] args) throws Exception
	{
		PurseApi.msQueue(8888, 11432923, Instant.now().getEpochSecond());
		Thread.sleep(10000);
		System.out.println(PurseApi.msQueueResult(8888));
	}

}
